<?php
/**
 * Date: 2017/11/7
 * Time: 18:19
 * Author: zeronlee
 */
namespace App\Http\Controllers\Backend\Access;

use App\Http\Controllers\Controller;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Models\Access\Permission\Permission;
use App\Http\Controllers\Traits\Base;
use Illuminate\Http\Response;

class PermissionController extends Controller
{
    use Base;
    /**
     * 首页
     */
    public function index (){
        $pageNum = 10;
        //模块
        $modular = Permission::getModular();
        return view('backend.access.permissionindex')->with('pageNum',$pageNum)->with('modular',$modular);
    }

    /**
     * 异步查询
     */
    public static function search(Request $request){

        $param = $request->input();

        //搜索
        $search = $param['search'];
        //记录数
        $count = Permission::getCount();

        //列表
        $permissions = Permission::getList('*',[$param['start'],$param['length']]);

        $data = array('draw'=>$param['draw'],'recordsTotal'=>$count,'recordsFiltered'=>$count,'data'=>$permissions);

        return response()->json($data);
    }
    /**
     * 存储
     */
    public function add (Request $request){
        $res['code'] = 0;
        $this->validate($request, [
            'code' => 'required|unique:permissions',
            'name' => 'required'
        ]);
        $data = $request->input();
        //如何自定义错误json返回

        $data['sort'] = 0;
        unset($data['id']);
        if (!Permission::insertRow($data)){
            $res['code'] = 403;
            $res['msg'] = '添加失败';
        }
        return response()->json($res);
    }

    /**
     * 更新
     */
    public function update (Request $request){
        $res['code'] = 0;
        $this->validate($request, [
            'code' => 'required',
            'name' => 'required'
        ]);
        $param = $request->input();

        $param['updated_at'] = Carbon::now();
        unset($param['code']);
        if(!Permission::updateRow(array('id',$param['id']),$param)){
            $res['code'] = 403;
            $res['msg'] = '修改失败';
        }
        return response()->json($res);
    }

    /**
     * 删除
     */
    public function delete (Request $request){
        $res['code'] = 0;
        $param = $request->input();

        if(!Permission::deleteRow(array('id',intval($param['id'])),$param)){
            $res['code'] = 403;
            $res['msg'] = '服务器忙';
        }
        return response()->json($res);
    }

}